package com.ErpCoreWeb.Workflow;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.ColumnType;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.Workflow.CActivesDef;
import com.ErpCoreModel.Workflow.CLink;
import com.ErpCoreModel.Workflow.CLinkMgr;
import com.ErpCoreModel.Workflow.CWorkflowDef;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class EditLink
 */
@WebServlet("/EditLink")
public class EditLink extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CUser m_User = null;
    public CTable m_Table = null;
    public CWorkflowDef m_WorkflowDef = null;
    public CCompany m_Company = null; 
    public CLinkMgr m_LinkMgr = null;
    public CActivesDef m_PreActives = null;
    public CLink m_BaseObject = null;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditLink() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User=(CUser)request.getSession().getAttribute("User");
        if (!m_User.IsRole("管理员"))
        {
        	try {
				response.getWriter().print("没有管理员权限！");
	        	response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	return ;
        }
		try {
			String B_Company_id = request.getParameter("B_Company_id");
			if (Global.IsNullParameter(B_Company_id))
				m_Company = Global.GetCtx(this.getServletContext())
						.getCompanyMgr().FindTopCompany();
			else
				m_Company = (CCompany) Global.GetCtx(this.getServletContext())
						.getCompanyMgr().Find(Util.GetUUID(B_Company_id));

			String wfid = request.getParameter("wfid");
			if (Global.IsNullParameter(wfid)) {
				response.getWriter().close();
				return;
			}
			m_WorkflowDef = (CWorkflowDef) m_Company.getWorkflowDefMgr().Find(
					Util.GetUUID(wfid));
			if (m_WorkflowDef == null) // 可能是新建的
			{
				if (request.getSession().getAttribute("AddWorkflowDef") == null) {
					response.getWriter().close();
					return;
				}
				m_WorkflowDef = (CWorkflowDef) request.getSession()
						.getAttribute("AddWorkflowDef");
			}
			String PreActives = request.getParameter("PreActives");
			m_PreActives = (CActivesDef)m_WorkflowDef.getActivesDefMgr().Find(Util.GetUUID(PreActives));

			m_LinkMgr = m_WorkflowDef.getLinkMgr();

			m_Table = m_LinkMgr.getTable();

			String id = request.getParameter("id");
			if (Global.IsNullParameter(id))
			{
				response.getWriter().close();
			    return;
			}
			m_BaseObject = (CLink)m_LinkMgr.Find(Util.GetUUID(id));
			if (m_BaseObject == null)
			{
				response.getWriter().close();
			    return;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
        	m_BaseObject.Cancel();
            return ;
        }
        else if (Action.equalsIgnoreCase("GetCondiction"))
        {
        	GetCondiction();
            return ;
        }
	}

    void PostData()
    {
    	List<CBaseObject> lstCol = m_Table.getColumnMgr().GetList();
        boolean bHasVisible = false;
        for (CBaseObject obj : lstCol)
        {
            CColumn col = (CColumn)obj;

            if (col.getCode().equalsIgnoreCase("id"))
                continue;
            else if (col.getCode().equalsIgnoreCase("Created"))
                continue;
            else if (col.getCode().equalsIgnoreCase("Creator"))
                continue;
            else if (col.getCode().equalsIgnoreCase("Updated"))
                continue;
            else if (col.getCode().equalsIgnoreCase("Updator"))
                continue;

            m_BaseObject.SetColValue(col, request.getParameter(col.getCode()));
            bHasVisible = true;
        }
        if (!bHasVisible)
        {
        	try {
				response.getWriter().print("没有可修改字段！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        CUser user = (CUser)request.getSession().getAttribute("User");
        m_BaseObject.setUpdator ( user.getId());
        m_LinkMgr.Update(m_BaseObject);
    }

    void GetCondiction()
    {
    	String Column = request.getParameter("Column");
        String Val = request.getParameter("Val");

        CTable table = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(m_WorkflowDef.getFW_Table_id());
        if (table == null)
            return;
        CColumn col = table.getColumnMgr().FindByName(Column);
        if (col == null)
            return;
        if (col.getColType() == ColumnType.int_type
                || col.getColType() == ColumnType.long_type
                || col.getColType() == ColumnType.numeric_type
                || col.getColType() == ColumnType.bool_type)
        {
        	if (Val.length()==0)
                Val = "0";
            else
            {
                try { Double.valueOf(Val); }
                catch(Exception e)
                {
                    return;
                }
            }
        }
        else
        {
            if (Val.length()==0)
                Val = "''";
            else
            {
                if (!Val.startsWith("\'"))
                    Val = "\'" + Val;
                if (!Val.endsWith("\'"))
                    Val += "\'";
            }
        }

        try {
			response.getWriter().print(Val);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

}
